import React, { useState, useEffect } from 'react';
import './PLCPanel.css';

const RULES_ENGINE_URL = 'http://localhost:3004';

export default function RuleEnginePanel() {
  const [rules, setRules] = useState([]);
  const [variables, setVariables] = useState({});
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  // 初始化规则引擎面板
  useEffect(() => {
    const initRuleEnginePanel = async () => {
      try {
        await fetchRules();
        await fetchVariables();
      } catch (err) {
        console.error('初始化规则引擎面板失败:', err);
        setError('初始化规则引擎面板失败: ' + err.message);
      }
    };

    initRuleEnginePanel();
    
    // 定期获取变量更新
    const interval = setInterval(() => {
      fetchVariables();
    }, 5000);
    
    return () => clearInterval(interval);
  }, []);

  // 获取所有规则
  const fetchRules = async () => {
    try {
      const response = await fetch(`${RULES_ENGINE_URL}/api/rules`);
      if (response.ok) {
        const rulesData = await response.json();
        setRules(rulesData);
      }
    } catch (err) {
      console.error('获取规则失败:', err);
    }
  };

  // 获取所有变量
  const fetchVariables = async () => {
    try {
      const response = await fetch(`${RULES_ENGINE_URL}/api/variables`);
      if (response.ok) {
        const variablesData = await response.json();
        setVariables(variablesData);
      }
    } catch (err) {
      console.error('获取变量失败:', err);
    }
  };

  // 添加规则
  const handleAddRule = async () => {
    const ruleName = prompt('请输入规则名称:');
    if (!ruleName) return;
    
    const rule = {
      name: ruleName,
      description: '新规则描述',
      condition: {
        variable: 'DB1,W0',
        operator: '===',
        value: 1
      },
      actions: [
        {
          type: 'log',
          message: `规则 ${ruleName} 触发`
        }
      ]
    };
    
    try {
      setLoading(true);
      const response = await fetch(`${RULES_ENGINE_URL}/api/rules`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(rule)
      });
      
      if (response.ok) {
        await fetchRules();
        alert('规则添加成功');
      } else {
        throw new Error('添加规则失败');
      }
    } catch (err) {
      setError('添加规则失败: ' + err.message);
      alert('添加规则失败: ' + err.message);
    } finally {
      setLoading(false);
    }
  };

  // 激活规则
  const handleActivateRule = async (ruleId) => {
    try {
      const response = await fetch(`${RULES_ENGINE_URL}/api/rules/${ruleId}/activate`, {
        method: 'POST'
      });
      
      if (response.ok) {
        await fetchRules();
        alert('规则已激活');
      } else {
        throw new Error('激活规则失败');
      }
    } catch (err) {
      setError('激活规则失败: ' + err.message);
      alert('激活规则失败: ' + err.message);
    }
  };

  // 停用规则
  const handleDeactivateRule = async (ruleId) => {
    try {
      const response = await fetch(`${RULES_ENGINE_URL}/api/rules/${ruleId}/deactivate`, {
        method: 'POST'
      });
      
      if (response.ok) {
        await fetchRules();
        alert('规则已停用');
      } else {
        throw new Error('停用规则失败');
      }
    } catch (err) {
      setError('停用规则失败: ' + err.message);
      alert('停用规则失败: ' + err.message);
    }
  };

  // 删除规则
  const handleDeleteRule = async (ruleId) => {
    if (!window.confirm('确定要删除此规则吗？')) return;
    
    try {
      const response = await fetch(`${RULES_ENGINE_URL}/api/rules/${ruleId}`, {
        method: 'DELETE'
      });
      
      if (response.ok) {
        await fetchRules();
        alert('规则已删除');
      } else {
        throw new Error('删除规则失败');
      }
    } catch (err) {
      setError('删除规则失败: ' + err.message);
      alert('删除规则失败: ' + err.message);
    }
  };

  // 更新变量
  const handleUpdateVariable = async () => {
    const varName = prompt('请输入变量名:');
    if (!varName) return;
    
    const varValue = prompt('请输入变量值:');
    if (varValue === null) return;
    
    try {
      setLoading(true);
      const response = await fetch(`${RULES_ENGINE_URL}/api/variables`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          variables: {
            [varName]: isNaN(varValue) ? varValue : Number(varValue)
          }
        })
      });
      
      if (response.ok) {
        await fetchVariables();
        alert('变量更新成功');
      } else {
        throw new Error('更新变量失败');
      }
    } catch (err) {
      setError('更新变量失败: ' + err.message);
      alert('更新变量失败: ' + err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="plc-panel">
      <h3>
        🤖 规则引擎控制面板
      </h3>
      
      {/* 错误信息显示 */}
      {error && (
        <div className="error-message">
          ❌ {error}
        </div>
      )}
      
      <div className="plc-status">
        <div className="status-buttons">
          <button 
            className="control-btn load-btn"
            onClick={handleAddRule}
            disabled={loading}
          >
            {loading ? '⏳ 添加中...' : '➕ 添加规则'}
          </button>
          <button 
            className="control-btn load-btn"
            onClick={handleUpdateVariable}
            disabled={loading}
          >
            {loading ? '⏳ 更新中...' : '🔄 更新变量'}
          </button>
        </div>
      </div>

      {/* 规则列表 */}
      <div className="plc-groups">
        <h4>规则列表</h4>
        
        {rules.length > 0 ? (
          <div className="group-content">
            {rules.map(rule => (
              <div key={rule.id} className="group-section">
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <h5>{rule.name}</h5>
                  <div>
                    <button
                      className="control-btn"
                      onClick={() => rule.active ? handleDeactivateRule(rule.id) : handleActivateRule(rule.id)}
                      style={{
                        backgroundColor: rule.active ? '#FF9800' : '#4CAF50',
                        color: 'white',
                        marginRight: '10px'
                      }}
                    >
                      {rule.active ? '⏸️ 停用' : '▶️ 激活'}
                    </button>
                    <button
                      className="control-btn"
                      onClick={() => handleDeleteRule(rule.id)}
                      style={{
                        backgroundColor: '#f44336',
                        color: 'white'
                      }}
                    >
                      🗑️ 删除
                    </button>
                  </div>
                </div>
                <p className="group-description">{rule.description}</p>
                
                <div style={{ marginBottom: '10px' }}>
                  <strong>状态:</strong> 
                  <span style={{ 
                    color: rule.active ? '#4CAF50' : '#FF9800',
                    fontWeight: 'bold',
                    marginLeft: '10px'
                  }}>
                    {rule.active ? '🟢 激活' : '🟡 停用'}
                  </span>
                </div>
                
                <div style={{ marginBottom: '10px' }}>
                  <strong>条件:</strong>
                  <pre style={{ 
                    backgroundColor: '#f5f5f5', 
                    padding: '10px', 
                    borderRadius: '4px',
                    fontSize: '12px',
                    overflow: 'auto'
                  }}>
                    {JSON.stringify(rule.condition, null, 2)}
                  </pre>
                </div>
                
                <div>
                  <strong>动作:</strong>
                  <pre style={{ 
                    backgroundColor: '#f5f5f5', 
                    padding: '10px', 
                    borderRadius: '4px',
                    fontSize: '12px',
                    overflow: 'auto'
                  }}>
                    {JSON.stringify(rule.actions, null, 2)}
                  </pre>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="no-groups">
            <p>暂无规则配置</p>
            <button 
              className="control-btn load-btn"
              onClick={handleAddRule}
              disabled={loading}
              style={{ marginTop: '10px' }}
            >
              {loading ? '⏳ 添加中...' : '➕ 添加示例规则'}
            </button>
          </div>
        )}
      </div>

      {/* 变量监控 */}
      <div className="plc-groups">
        <h4>变量监控</h4>
        
        {Object.keys(variables).length > 0 ? (
          <div className="group-content">
            <div className="results-grid">
              {Object.entries(variables).map(([name, value]) => (
                <div key={name} className="result-item">
                  <span className="result-name" title={name}>{name}:</span>
                  <span className="result-value" title={value}>
                    {typeof value === 'boolean' ? (value ? 'true' : 'false') : String(value)}
                  </span>
                </div>
              ))}
            </div>
          </div>
        ) : (
          <div className="no-groups">
            <p>暂无变量数据</p>
            <p style={{ fontSize: '14px', color: '#666', marginTop: '10px' }}>
              提示：可以通过PLC服务或Node-RED向规则引擎发送变量更新
            </p>
          </div>
        )}
      </div>

      <div className="plc-info">
        <h4>使用说明</h4>
        <ul>
          <li>规则引擎基于条件判断自动执行动作</li>
          <li>支持PLC变量监控和自动控制</li>
          <li>可通过Node-RED进行可视化编程</li>
          <li>规则引擎地址: http://localhost:3004</li>
          <li>Node-RED地址: http://localhost:1880</li>
        </ul>
        
        <h4>Node-RED集成说明</h4>
        <ul>
          <li>在Node-RED中可以通过HTTP请求节点向规则引擎发送变量更新</li>
          <li>规则引擎会根据变量变化自动评估规则条件</li>
          <li>满足条件的规则会自动执行预定义的动作</li>
          <li>支持PLC写入、数据库操作、日志记录等多种动作类型</li>
        </ul>
      </div>
    </div>
  );
}